package com.h.rabbitmq.controller;

import com.h.rabbitmq.constants.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 消息的生产者
 */
@RestController
@RequestMapping("/producer")
public class ProduceController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/work")
    public String work() {
        // 使用内置的交换机，所以这里交换机为空
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("", Constants.WORK_QUEUE,"hello spring amqp:work..." + i);
        }
        return "发送成功";
    }

    @RequestMapping("/fanout")
    public String fanout() {
        // routingKey为空, 表⽰所有队列都可以收到消息
        rabbitTemplate.convertAndSend(Constants.FANOUT_EXCHANGE, "", "hello spring amqp:fanout...");
        return "发送成功";
    }

    @RequestMapping("/direct/{routingKey}")
    // 从url中获取routingKey 赋值到参数中利用 @PathVariable 这个注解
    public String direct(@PathVariable("routingKey") String routingKey) {
        rabbitTemplate.convertAndSend(Constants.DIRECT_EXCHANGE, routingKey,
                "hello spring amqp:direct, my routing key is "+routingKey);
        return "发送成功";
    }

    @RequestMapping("/topic/{routingKey}")
    public String topic(@PathVariable("routingKey") String routingKey) {
        rabbitTemplate.convertAndSend(Constants.TOPIC_EXCHANGE, routingKey,
                "hello spring amqp:topic, my routing key is "+routingKey);
        return "发送成功";
    }
}
